package ua.kharkov.khpi.tarasenko.bach.core.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import ua.kharkov.khpi.tarasenko.bach.core.EShopException;

/**
 * Creates connection to data base.
 * 
 * @author oleksandr
 * 
 */
public class ConnectionManager {

	private static DataSource ds;

	/**
	 * Initializing connection manager.
	 * 
	 * @param dataSource
	 *            - factory for connections.
	 * @throws IllegalAccessException
	 *             - if connection manager already initialized.
	 */
	public static void init(DataSource dataSource)
			throws IllegalAccessException {
		if (!isInitialized()) {
			ds = dataSource;
		} else {
			throw new IllegalAccessException(
					"Connection Manager already initialized!");
		}
	}

	/**
	 * Returns connection to database.
	 * 
	 * @return connection
	 * @throws EShopException
	 *             - if connection manager isn't initialized!
	 * @throws EShopDataStoreException
	 *             - if can't get connection.
	 */
	public static synchronized Connection getConnection()
			throws EShopException{

		if (!isInitialized()) {
			throw new EShopException(
					"Connection Manager isn't initialized!");
		}
		Connection conn = null;
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			throw new EShopDataStoreException(
					"Error occured during getting connection to database", e);
		}

		return conn;
	}

	public static boolean isInitialized() {
		if (ds != null) {
			return true;
		} else {
			return false;
		}
	}
}
